package com.tax.common.tool.impli;


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JavaIdentifierTransformer;

import org.apache.log4j.Logger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import com.tax.common.tool.IToolWrap;
import com.tax.common.tool.option.img.IImageScale;
import com.tax.common.tool.option.img.impli.ImageScale;
import com.tax.common.tool.option.secure.ISafe;
import com.tax.common.tool.option.secure.code.SafeOneImpli;

import sun.net.util.IPAddressUtil;



public class ToolWrap implements IToolWrap {
	private Logger log = Logger.getLogger(ToolWrap.class.getName());
	
	private ISafe safe=new SafeOneImpli();
	private IImageScale imageScale=new ImageScale();
	
	private List<String> someListStrings;

	
	@Override
	public String getString2MD5(String str) {
		return safe.getString2MD5(str);
	}

	@Override
	public String getFile2MD5(File file) {
		return safe.getFile2MD5(file);
	}

	@Override
	public String getKey(String password) {
		return safe.getKey(password);
	}

	@Override
	public String getCiphertext(String accountPassword, String key) {
		return safe.getCiphertext(accountPassword, key);
	}

	@Override
	public String deciphering(String Ciphertext, String key) {
		return safe.deciphering(Ciphertext, key);
	}

	@Override
	public void resizeFix(File imgPath, File scalImgPath, int width, int height) {
		imageScale.resizeFix(imgPath, scalImgPath, width, height);
	}

	@Override
	public String shifting(String needShifting, int offset) {
		char [] arrays=needShifting.toCharArray();
		for(int i=0;i<arrays.length;i++){
			arrays[i]=(char)(arrays[i]^offset);
		}
		return new String(arrays);
	}

	@Override
	public void copyToClipboard(String content) {
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		StringSelection  selection = new StringSelection(content);
		clipboard.setContents(selection, null);
	}

	@Override
	public String getContetFromClipboard() {
		String content="";
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable clipData=clipboard.getContents(clipboard);
		try{
			content=(String)(clipData.getTransferData(DataFlavor.stringFlavor));
			log.info("剪切板内容为："+content);
		}catch(IOException VariableDeclaratorId){} catch (UnsupportedFlavorException e) {
			e.printStackTrace();
		}
		return content;
	}

	@Override
	public String ZipCompressorByAnt(String srcPathName) {
		File srcdir = new File(srcPathName); 
		String zipFileStr="";
		
		if(srcdir.isDirectory()){
			zipFileStr=srcPathName+".zip";
		}else{
			int index=srcPathName.lastIndexOf(".");
			if(index>0)
				zipFileStr=srcPathName.substring(0,index)+".zip";
			else
				zipFileStr=srcPathName+".zip";
		}
		
		File zipFile;
		if(zipFileStr.length()>0){
			zipFile = new File(zipFileStr);
			   
	        if (!srcdir.exists()){  
	        	zipFileStr="";
	            throw new RuntimeException(srcPathName + "不存在！");  
	        }   
	        Project prj = new Project();    
	        Zip zip = new Zip();    
	        zip.setProject(prj);    
	        zip.setDestFile(zipFile);    
	        FileSet fileSet = new FileSet();    
	        fileSet.setProject(prj);    
	        fileSet.setDir(srcdir);    
	        //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");    
	        //fileSet.setExcludes(...); //排除哪些文件或文件夹    
	        zip.addFileset(fileSet);    
	        zip.execute(); 
		}else{
			return "";
		}
		return zipFileStr;
	}
	
	@Override
	public void unZipByAnt(String zipFilePath, String fileSavePath,
			boolean isDelete) {
		try {  
            (new File(fileSavePath)).mkdirs();  
            File f = new File(zipFilePath);  
            if ((!f.exists()) && (f.length() <= 0)) {  
                throw new Exception("要解压的文件不存在!");  
            }  
            ZipFile zipFile = new ZipFile(f);  
            String strPath, gbkPath, strtemp;  
            File tempFile = new File(fileSavePath);// 从当前目录开始  
            strPath = tempFile.getAbsolutePath();// 输出的绝对位置  
            Enumeration<ZipEntry> e = zipFile.getEntries();  
            while (e.hasMoreElements()) {  
                org.apache.tools.zip.ZipEntry zipEnt = e.nextElement();  
                gbkPath = zipEnt.getName();  
                if (zipEnt.isDirectory()) {  
                    strtemp = strPath + File.separator + gbkPath;  
                    File dir = new File(strtemp);  
                    dir.mkdirs();  
                    continue;  
                } else {  
                    // 读写文件  
                    InputStream is = zipFile.getInputStream(zipEnt);  
                    BufferedInputStream bis = new BufferedInputStream(is);  
                    gbkPath = zipEnt.getName();  
                    strtemp = strPath + File.separator + gbkPath;  
                    // 建目录  
                    String strsubdir = gbkPath;  
                    for (int i = 0; i < strsubdir.length(); i++) {  
                        if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {  
                            String temp = strPath + File.separator + strsubdir.substring(0, i);  
                            File subdir = new File(temp);  
                            if (!subdir.exists())  
                                subdir.mkdir();  
                        }  
                    }  
                    FileOutputStream fos = new FileOutputStream(strtemp);  
                    BufferedOutputStream bos = new BufferedOutputStream(fos);  
                    int len;  
                    byte[] buff = new byte[2048];  
                    while ((len = bis.read(buff)) != -1) {  
                        bos.write(buff, 0, len);  
                    }  
                    bos.close();  
                    fos.close();  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if (isDelete) {  
            new File(zipFilePath).delete();  
        }  
		
	}


	@Override
	public String baiduApi(String httpUrl, String httpArg) {
		BufferedReader reader = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey", "96c0f7cb84fd2b8e8281d1870709373a");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        log.info("服务器返回的数据："+sbf);
	        reader.close();
	        is.close();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return sbf.toString();
	}
	

	@Override
	public String strToBase64Str(String str) {
		return safe.strToBase64Str(str);
	}
	
	

	@SuppressWarnings("rawtypes")
	@Override
	public Object jsonToObject(String jsonStr, Class obj) {
		JsonConfig config = new JsonConfig();
		config.setJavaIdentifierTransformer(new JavaIdentifierTransformer() {

            @Override
            public String transformToJavaIdentifier(String str) {//这方法解决首字母大写问题会抛异常的情况
                char[] chars = str.toCharArray();
                chars[0] = Character.toLowerCase(chars[0]);
                return new String(chars);
            }
        });
		config.setRootClass(obj);
		JSONObject jsonObject=JSONObject.fromObject(jsonStr);
		
		return JSONObject.toBean(jsonObject, config);
	}

	@Override
	public String getComputerUserName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getInputStream2MD5(InputStream inputStream) {
		// TODO Auto-generated method stub
		return safe.getInputStream2MD5(inputStream);
	}
	
	

	@Override
	public boolean internalIp(String ip) {
		byte[] addr = IPAddressUtil.textToNumericFormatV4(ip);
		final byte b0 = addr[0];
	    final byte b1 = addr[1];
	    //10.x.x.x/8
	    final byte SECTION_1 = 0x0A;
	    //172.16.x.x/12
	    final byte SECTION_2 = (byte) 0xAC;
	    final byte SECTION_3 = (byte) 0x10;
	    final byte SECTION_4 = (byte) 0x1F;
	    //192.168.x.x/16
	    final byte SECTION_5 = (byte) 0xC0;
	    final byte SECTION_6 = (byte) 0xA8;
	    switch (b0) {
	        case SECTION_1:
	            return true;
	        case SECTION_2:
	            if (b1 >= SECTION_3 && b1 <= SECTION_4) {
	                return true;
	            }
	        case SECTION_5:
	            switch (b1) {
	                case SECTION_6:
	                    return true;
	            }
	        default:
	            return false;
	    }
	}

	@Override
	public String getPublicIp() {
		String ip=null;
		try {
			String txtString=getUrlResponseTXT("http://city.ip138.com/ip2city.asp");
			if(txtString!=null&&txtString.length()>5){
				int indexS=txtString.indexOf("[");
				int indexE=txtString.lastIndexOf("]");
				if(indexS!=-1&&indexE!=-1)
					ip=txtString.substring(indexS+1, indexE);
			}
			if(ip==null||ip.equals("")||ip.length()<5){
				txtString=getUrlResponseTXT("http://www.ip38.com/");
				int indexS=txtString.indexOf("[<font color=#ff0000>");
				int indexE=txtString.lastIndexOf("]");
				if(indexS!=-1&&indexE!=-1&&indexS<indexE){
					txtString=txtString.substring(indexS+1, indexE);
					indexS=txtString.indexOf(">");
					indexE=txtString.lastIndexOf("<");
					if(indexS!=-1&&indexE!=-1&&indexS<indexE){
						txtString=txtString.substring(indexS+1, indexE);
						ip=txtString;
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return ip;
	}

	@Override
	public String getUrlResponseTXT(String urlStr) {
		try {
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();

			con.setInstanceFollowRedirects(false);
			con.setUseCaches(false);
			con.setAllowUserInteraction(false);
			con.connect();
			StringBuffer sb = new StringBuffer();
			String line = "";
			BufferedReader URLinput = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "Gb2312"));
			while ((line = URLinput.readLine()) != null) {
				sb.append(line);
			}
			con.disconnect();

			return sb.toString().toLowerCase();
		} catch (Exception e) {

			return null;
		}
	}

	@Override
	public void sendMail(String toEmailAddr, String password,String theme,String content) {
		// TODO Auto-generated method stub
		// 配置发送邮件的环境属性
		final Properties props = new Properties();
		/*
		 * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
		 * mail.user / mail.from
		 */
		// 表示SMTP发送邮件，需要进行身份验证
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", "smtp.126.com");
		// 发件人的账号
		props.put("mail.user", "message_dadiwm321@126.com");
		// 访问SMTP服务时需要提供的密码
		props.put("mail.password", password);

		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 使用环境属性和授权信息，创建邮件会话
		Session mailSession = Session.getInstance(props, authenticator);
		// 创建邮件消息
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form;
		try {
			form = new InternetAddress(
					props.getProperty("mail.user"));
			message.setFrom(form);
			// 设置收件人
			InternetAddress to = new InternetAddress(toEmailAddr);
			message.setRecipient(RecipientType.TO, to);
			// 设置抄送
			// InternetAddress cc = new InternetAddress("luo_aaaaa@yeah.net");
			// message.setRecipient(RecipientType.CC, cc);
			//
			// // 设置密送，其他的收件人不能看到密送的邮件地址
			// InternetAddress bcc = new InternetAddress("aaaaa@163.com");
			// message.setRecipient(RecipientType.CC, bcc);

			// 设置邮件标题
			message.setSubject(theme);

			// 设置邮件的内容体
			message.setContent(content,"text/html;charset=UTF-8");

			// 发送邮件
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public List<String> getRelativeFilePath(File dir,String enumType) {
		someListStrings=new ArrayList<String>();
		listF(dir, "",enumType);
		return someListStrings;
	}
	
	public void listF(File dir,String dirNameString,String enumType){
		File f[]=dir.listFiles();
		
		for (File file : f) {
			if (file.isDirectory()) {
				String dirstr=dirNameString+file.getName()+"/";
				listF(file, dirstr,enumType);
			}else{
				String fileName=file.getName().toLowerCase();
				if (enumType!=null&&enumType.equalsIgnoreCase("movie")) {
					if (fileName.endsWith(".mp4")||fileName.endsWith(".avi")||
							fileName.endsWith(".rmvb")||fileName.endsWith(".mkv")||
							fileName.endsWith(".wmv")) {
						someListStrings.add(dirNameString+file.getName());
					}
				}else if (enumType!=null&&enumType.equalsIgnoreCase("img")) {
					if (fileName.endsWith(".png")||fileName.endsWith(".gif")||
							fileName.endsWith(".jpg")||fileName.endsWith(".jpeg")||
							fileName.endsWith(".bmp")) {
						someListStrings.add(dirNameString+file.getName());
					}
				}else{
					someListStrings.add(dirNameString+file.getName());
				}
			}
		}
	}
	public static void main(String arg[]) throws UnsupportedEncodingException{
		ToolWrap t=new ToolWrap();
		t.sendMail("805015623@qq.com", "","", "iii");
	}
}
